package com.czk.scala.chapter04

/**
 * @Author:ChenZhangKun
 * @Date: 2021/12/7 14:52
 */
object Test02_ForLoop {
  def main(args: Array[String]): Unit = {
    // for 的范围遍历
    for (i <- 0 to 9) {
      println(i)
    }
    // 本质也是方法调用
    // i 会被隐式转换为RichInt
    for (i: Int <- 0.to(9)) {
      println(i)
    }

    // 直接定义range
    for (i: Int <- Range(1, 10)) {
      print(i + " ")
    }
    // util不包括边界
    for (i: Int <- 1 until 10) {
      print(i + " ")
    }
    println()
    // 集合遍历
    for (i: Int <- Array(140, 150, 160)) {
      println(i)
    }

    println("==================循环守卫============")
    // 相当如省略的java中额continue关键字
    for (i <- 1 to 10 if i != 5) {
      println(i)
    }

    println("=========循环步长============")
    // 指定步长为2
    for (i <- 1 to 10 by 2) {
      println(i)
    }
    // 倒序输出，定义步长为负数->类似于py的字符串切割
    for (i <- 10 to 1 by -2) {
      println(i)
    }
    // 倒序遍历
    for (i <- 1 to 10 reverse) {
      println(i)
    }
    // 步长为小数
    for (i <- 1.0 to 10.0 by 0.5) {
      println(i)
    }

    // 99 乘法表的输出
    for (i <- 1 to 9) {
      println()
      for (j <- 1 to i) {
        print(s"${j} * ${i} = " + i * j + "\t")
      }
    }
    println()
    // 简写
    for (i <- 1 to 9; j <- 1 to i) {
      print(s"${j} * ${i} = " + i * j + "\t")
      if (j == i) println()
    }
    // 循环引用变量
    for (i: Int <- 1 to 10) {
      val j = 10 - i
      println("i= " + i + ",j=" + j)
    }


    for (i: Int <- 1 to 10; j = 10 - i) {
      println("i= " + i + ",j=" + j)
    }
    // 分行写法
    for {
      i <- 1 to 10
      j = 10 - i
    } {
      println("i= " + i + ",j=" + j)
    }


    // 循环返回值
    val a: Unit = for (i <- 1 to 10) {
      println(i)
    }
    // ()
    println(a)
    // 生成一个集合类型
    val b = for (i <- 1 to 10) yield i * 2
    println(b)
  }
}
